import React, { useState, useEffect, useRef } from "react";
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Row,
  Col,
  List,
  InputNumber,
  message,
} from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import styles from "../index.less";
import { auth } from "@/utils/auth";

const { TextArea } = Input;
const { Option } = Select;

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
  createdAt: string;
}

interface ConfigFormValues {
  userId: string;
  name: string;
  gender: string;
  alias: string;
  placeOfOrigin: string;
  profession: string;
  age: number;
  style: string;
  other: string;
  goal: string;
  template: string;
  notes: string;
}

const ChatTest: React.FC = () => {
  const [chatForm] = Form.useForm();
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
  const [inputMessage, setInputMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [sendLoading, setSendLoading] = useState(false);
  const [clearLoading, setClearLoading] = useState(false);
  const sessionId = "string"; // 可以根据需要修改
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const userId = auth.getUserId();

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop =
        chatContainerRef.current.scrollHeight;
    }
  }, [chatMessages]);

  // 获取聊天记录
  const fetchChatHistory = async () => {
    try {
      setLoading(true);
      const response = await fetch(
        `/agentai/chat/${userId}?sessionId=${sessionId}`
      );

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          setChatMessages(result.data);
        } else {
          message.error(result.message || "获取聊天记录失败");
        }
      } else {
        message.error("获取聊天记录失败");
      }
    } catch (error) {
      message.error("获取聊天记录失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  const fetchAgent = async () => {
    const response = await fetch("/agentai/agent/" + auth.getUserId(), {
      method: "GET",
    });
    if (response.status === 200) {
      const result = await response.json();
      if (result.code === 200 && result.data) {
        chatForm.setFieldsValue(result.data);
      } else {
        message.error(result.message || "获取sessionId失败");
      }
    }
  };

  // 组件加载时获取聊天记录
  useEffect(() => {
    fetchChatHistory();
    fetchAgent();
  }, []);

  const handleChatConfig = async (values: ConfigFormValues) => {
    try {
      setLoading(true);

      const response = await fetch("/agentai/agent", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          name: values.name,
          gender: values.gender,
          alias: values.alias,
          placeOfOrigin: values.placeOfOrigin,
          profession: values.profession,
          age: values.age,
          style: values.style,
          other: values.other,
          goal: values.goal,
          template: values.template,
          notes: values.notes,
        }),
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          message.success("配置成功");
        } else {
          message.error(result.message || "配置失败");
        }
      } else {
        message.error("配置失败");
      }
    } catch (error) {
      message.error("配置失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;

    try {
      setSendLoading(true);
      // 立即添加用户消息到列表
      const userMessage: ChatMessage = {
        role: "user",
        content: inputMessage,
        createdAt: new Date().toISOString(),
      };
      setChatMessages((prev) => [...prev, userMessage]);
      setInputMessage(""); // 清空输入框

      const response = await fetch("/agentai/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          sessionId: sessionId,
          message: inputMessage,
          username: chatForm.getFieldValue("name") || "用户",
        }),
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          // 添加AI回复到列表
          const aiMessage: ChatMessage = {
            role: "assistant",
            content: result.data.content,
            createdAt: new Date().toISOString(),
          };
          setChatMessages((prev) => [...prev, aiMessage]);
        } else {
          message.error(result.message || "发送失败");
        }
      } else {
        message.error("发送失败");
      }
    } catch (error) {
      message.error("发送失败，请检查网络连接");
    } finally {
      setSendLoading(false);
    }
  };

  const handleClearChat = async () => {
    try {
      setClearLoading(true);
      const response = await fetch(
        `/agentai/chat/${userId}?sessionId=${sessionId}`,
        {
          method: "DELETE",
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          setChatMessages([]);
          message.success("清空成功");
        } else {
          message.error(result.message || "清空失败");
        }
      } else {
        message.error("清空失败");
      }
    } catch (error) {
      message.error("清空失败，请检查网络连接");
    } finally {
      setClearLoading(false);
    }
  };

  return (
    <Row gutter={24}>
      <Col span={12}>
        <Card title="AI分身设定">
          <div className={styles.colcard}>
            <Form
              form={chatForm}
              layout="horizontal"
              onFinish={handleChatConfig}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
            >
              <Form.Item
                label="姓名"
                name="name"
                rules={[
                  { required: true, message: "请输入姓名" },
                  { max: 10, message: "不能超过10个字" },
                ]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>

              <Form.Item
                label="性别"
                name="gender"
                rules={[{ required: true, message: "请选择性别" }]}
              >
                <Select placeholder="请选择性别">
                  <Option value="男">男</Option>
                  <Option value="女">女</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="alias"
                label="别名"
                rules={[{ max: 10, message: "不能超过10个字" }]}
              >
                <Input placeholder="请输入别名" />
              </Form.Item>

              <Form.Item
                name="placeOfOrigin"
                label="籍贯"
                rules={[{ max: 20, message: "不能超过20个字" }]}
              >
                <Input placeholder="请输入籍贯" />
              </Form.Item>

              <Form.Item
                name="profession"
                label="职业"
                rules={[{ max: 10, message: "不能超过10个字" }]}
              >
                <Input placeholder="请输入职业" />
              </Form.Item>

              <Form.Item label="年龄" name="age">
                <InputNumber
                  min={1}
                  max={150}
                  placeholder="请输入年龄"
                  style={{ width: "100%" }}
                />
              </Form.Item>

              <Form.Item
                name="style"
                label="讲话风格"
                rules={[{ required: true, message: "请选择讲话风格" }]}
              >
                <Select placeholder="请选择讲话风格">
                  <Option value="幽默">幽默</Option>
                  <Option value="严肃">严肃</Option>
                  <Option value="温柔">温柔</Option>
                  <Option value="活泼">活泼</Option>
                </Select>
              </Form.Item>

              <Form.Item
                label="其他补充背景"
                name="other"
                rules={[{ max: 100, message: "不能超过100个字" }]}
              >
                <TextArea
                  rows={4}
                  placeholder="是一名汽车销售行业的从业者，从业十年，在宝马也曾任职"
                />
              </Form.Item>

              <Form.Item
                label="目标"
                name="goal"
                rules={[{ max: 100, message: "不能超过100个字" }]}
              >
                <TextArea rows={4} placeholder="请输入目标" />
              </Form.Item>

              <Form.Item
                name="template"
                label="场景案例"
                rules={[{ max: 1500, message: "不能超过1500个字" }]}
              >
                <TextArea
                  rows={6}
                  placeholder="问：积分是什么？答：数字资产，可以即时秒用，跨界支付"
                />
              </Form.Item>

              <Form.Item
                label="回复注意事项"
                name="notes"
                rules={[{ max: 100, message: "不能超过100个字" }]}
              >
                <TextArea
                  rows={4}
                  placeholder="礼貌，高情商，注意拉扯，不要直接告诉价格，不要说失败案例"
                />
              </Form.Item>

              <Form.Item
                style={{ textAlign: "center" }}
                wrapperCol={{ span: 24 }}
              >
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ width: "60%" }}
                  loading={loading}
                >
                  配置
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Col>
      <Col span={12}>
        <Card
          title="测试对话"
          extra={
            <Button
              type="text"
              icon={<DeleteOutlined />}
              onClick={handleClearChat}
              loading={clearLoading}
            >
              清空对话
            </Button>
          }
        >
          <div className={styles.colcard}>
            <div
              style={{
                height: "calc(100% - 50px)",
                overflowY: "auto",
                marginBottom: "16px",
                scrollbarWidth: "none",
              }}
              ref={chatContainerRef}
            >
              <List
                loading={loading}
                itemLayout="horizontal"
                dataSource={chatMessages}
                renderItem={(message) => (
                  <List.Item
                    style={{
                      justifyContent:
                        message.role === "user" ? "flex-end" : "flex-start",
                      border: "none",
                    }}
                  >
                    <div
                      style={{
                        padding: "10px",
                        maxWidth: "80%",
                        backgroundColor:
                          message.role === "user" ? "#e6f7ff" : "#f5f5f5",
                      }}
                    >
                      <div>{message.content}</div>
                    </div>
                  </List.Item>
                )}
              />
            </div>
            <div style={{ display: "flex", gap: "8px" }}>
              <Input
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault();
                    handleSendMessage();
                  }
                }}
                placeholder="请输入消息"
                disabled={sendLoading}
              />
              <Button
                type="primary"
                onClick={handleSendMessage}
                loading={sendLoading}
              >
                发送
              </Button>
            </div>
          </div>
        </Card>
      </Col>
    </Row>
  );
};

export default ChatTest;
